import React from "react"
import { Avatar, Dropdown, message } from "antd"
import { UserOutlined } from "@ant-design/icons"
import useUserStore from "@/stores/user"
import { userLoginOut } from "@/api/auth"
import { TOKEN } from "@/constants"
import { useNavigate } from "react-router"
import "./index.scss"
import type { MenuProps } from "antd"

/**
 * 全局头部
 */
const GlobalHeader: React.FC = () => {
  const navigate = useNavigate()
  const { currentUser, setCurrentUser } = useUserStore()

  const handleLogout = async () => {
    try {
      const res = await userLoginOut()
      if (res.data) {
        setCurrentUser(null)
        localStorage.removeItem(TOKEN)
        navigate("/login", { replace: true })
        message.success("退出登录成功")
      }
    } catch (e: any) {
      message.error("退出登录失败，" + e.message)
    }
  }

  const items: MenuProps["items"] = [
    {
      key: "setting",
      label: "设置"
    },
    {
      key: "logout",
      label: "退出登录",
      onClick: handleLogout
    }
  ]

  return (
    <div className="global-header">
      <div className="global-header__toolbar">
        <Dropdown menu={{ items }}>
          <div>
            <Avatar size={28} icon={<UserOutlined />} />
            <span className="userName">{currentUser?.userName ?? "未登录"}</span>
          </div>
        </Dropdown>
      </div>
    </div>
  )
}

export default GlobalHeader
